import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import '../pages/home/HomePage.dart';

class TabBarPage extends StatefulWidget {
  const TabBarPage({Key? key}) : super(key: key);

  @override
  _TabBarPageState createState() => _TabBarPageState();
}

class _TabBarPageState extends State<TabBarPage> {
  // 定义tabList数据
  List tabList = [
    {
      'label': '首页',
      'activeIcon': '/tabbar/home-active.png',
      'icon': '/tabbar/home.png',
    },
    {
      'label': '分类',
      'activeIcon': '/tabbar/cate-active.png',
      'icon': '/tabbar/cate.png',
    },
    {
      'label': '购物车',
      'activeIcon': '/tabbar/cart-active.png',
      'icon': '/tabbar/cart.png',
    },
    {
      'label': '我的',
      'activeIcon': '/tabbar/user-active.png',
      'icon': '/tabbar/user.png',
    }
  ];

  Widget getBody() {
    if (currentIndex == 0) {
      return HomePage();
    } else if (currentIndex == 1) {
      return Center(child: Text("分类"));
    } else if (currentIndex == 2) {
      return Center(child: Text("购物车"));
    } else {
      return Center(child: Text("我的"));
    }
  }

  List<BottomNavigationBarItem> getTabBarList() {
    List<BottomNavigationBarItem> list = [];
    for (var i = 0; i < tabList.length; i++) {
      list.add(BottomNavigationBarItem(
          label: tabList[i]["label"],
          icon: Image.asset(
            tabList[i]["icon"],
            width: 40,
            height: 40,
          ),
          activeIcon: Image.asset(
            tabList[i]["activeIcon"],
            width: 40,
            height: 40,
          )));
    }
    return list;
  }

  int currentIndex = 0; //激活选项索引

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: const Text(
            "Flutter的Tabs案例",
          ),
          backgroundColor: Colors.blue,
          foregroundColor: Colors.white),
      body: getBody(),
      // IndexedStack(
      //   index: currentIndex,
      //   children: [
      //     Center(child: Text("首页")),
      //     Center(child: Text("分类")),
      //     Center(child: Text("购物车")),
      //     Center(child: Text("我的")),
      //   ],
      // ),
      bottomNavigationBar: BottomNavigationBar(
        items: getTabBarList(),
        // 将底部导航栏的类型设置为固定样式，
        type: BottomNavigationBarType.fixed,
        //  设置底部导航栏中被选中项的文字和图标颜色为红色
        selectedItemColor: Colors.red,
        // 设置底部导航栏中未被选中项的文字和图标颜色为黑色
        unselectedItemColor: Colors.black,
        // 用于指定当前处于选中状态的底部导航栏选项的索引值，
        currentIndex: currentIndex,
        // 点击切换索引值
        onTap: (int index) {
          setState(() {
            currentIndex = index;
          });
        },
      ),
    );
  }
}
